<template>
  <div class="test-case-editor">
    <!-- 顶部导航栏 -->
    <div class="header">
      <!-- <div class="project-info">
        <span class="project-name">演示的项目</span>
        <el-button type="text" @click="showProjectList">切换项目</el-button>
      </div> -->
      <div class="nav-tabs">
        <el-tabs v-model="activeTab">
          <!-- <el-tab-pane label="项目模块" name="module"></el-tab-pane>
          <el-tab-pane label="项目列表" name="project"></el-tab-pane>
          <el-tab-pane label="用例列表" name="case"></el-tab-pane> -->
          <el-tab-pane label="编辑用例" name="edit"></el-tab-pane>
        </el-tabs>
      </div>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
      <!-- 左侧操作面板 -->
      <div class="operation-panel">
        <div class="panel-title">
          <el-icon><component :is="`Edit`"></component></el-icon>
          <span>操作选项</span>
        </div>

        <!-- 元素操作分类 -->
        <div class="category-container">
          <div class="category-title">
            <el-icon><component :is="`Edit`"></component></el-icon>
            <span>元素操作</span>
          </div>

          <div class="operation-items">
            <div
              class="operation-item"
              v-for="item in elementOperations"
              :key="item.name"
              draggable="true"
              @dragstart="onDragStart($event, item)"
              @dragend="onDragEnd"
            >
              <div class="operation-icon">
                <el-icon>
                  <component :is="item.icon" v-if="item.icon"></component>
                </el-icon>
              </div>
              <span>{{ item.label }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧编辑区 -->
      <div class="editor-panel">
        <div class="editor-header">
          <el-input
            v-model="testCaseName"
            placeholder="输入用例名称"
            size="large"
            class="case-name-input"
          >
            <template #prepend>
              <el-icon><component :is="`Edit`"></component></el-icon>
            </template>
          </el-input>
        </div>

        <div class="steps-container" @dragover.prevent @drop="handleStepDrop">
          <div v-if="testSteps.length === 0" class="empty-placeholder">
            <el-icon size="50"><component :is="`Edit`"></component></el-icon>
            <p>请从左侧拖拽操作到此处</p>
          </div>

          <VueDraggable
            v-model="testSteps"
            handle=".drag-handle"
            item-key="id"
            :animation="200"
            ghost-class="ghost"
            @start="drag = true"
            @end="drag = false"
          >
            <div
              v-for="element in testSteps"
              :key="element.id"
              class="cursor-move h-30 bg-gray-500/5 rounded p-3"
            >
              <!-- <template #item="{ element, index }"> -->
              <div class="step-item">
                <div class="step-header">
                  <el-icon class="drag-handle">
                    <component :is="`Edit`"></component>
                  </el-icon>
                  <div class="step-index">{{ element.id }}</div>
                  <div class="step-title">{{ element.name }}</div>
                </div>

                <div class="step-details">
                  <div
                    v-for="(value, key) in element.params"
                    :key="key"
                    class="step-param"
                  >
                    <div class="param-key">{{ paramLabels[key] || key }}:</div>
                    <div class="param-value">{{ value }}</div>
                  </div>
                </div>

                <div class="step-actions">
                  <el-button
                    type="primary"
                    size="small"
                    @click="editStep(element)"
                  >
                    <el-icon><component :is="`Edit`"></component></el-icon>
                    编辑
                  </el-button>
                  <el-button
                    type="danger"
                    size="small"
                    @click="removeStep(element.id)"
                  >
                    <el-icon><component :is="`Edit`"></component></el-icon>
                    删除
                  </el-button>
                </div>
              </div>
              <!-- </template> -->
            </div>
          </VueDraggable>
        </div>

        <div class="editor-footer">
          <el-button type="primary" size="large" @click="saveTestCase">
            <el-icon><component :is="`Edit`"></component></el-icon>
            保存用例
          </el-button>
          <el-button size="large" @click="cancelEdit">
            <el-icon><component :is="`Edit`"></component></el-icon>
            取消编辑
          </el-button>
        </div>
      </div>
    </div>

    <!-- 步骤配置弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="`${editingStep !== null ? '编辑' : '添加'}操作`"
      width="600px"
      destroy-on-close
      class="step-config-dialog"
    >
      <div class="dialog-content">
        <div class="operation-title">
          <div class="operation-icon-large">
            <el-icon size="24">
              <component
                :is="operationIcons[editingStepType] || 'el-icon-setting'"
              ></component>
            </el-icon>
          </div>
          <h3>{{ form.name }}</h3>
        </div>

        <el-form :model="form" label-width="120px">
          <el-form-item label="操作名称" required>
            <el-input v-model="form.name" placeholder="请输入操作名称" />
          </el-form-item>

          <el-form-item
            v-for="param in requiredParams"
            :key="param"
            :label="paramLabels[param] || param"
            required
          >
            <el-input
              v-model="form.params[param]"
              :placeholder="`请输入${paramLabels[param] || param}`"
            />
          </el-form-item>

          <el-form-item
            v-for="param in optionalParams"
            :key="param"
            :label="paramLabels[param] || param"
          >
            <el-input
              v-model="form.params[param]"
              :placeholder="`请输入${paramLabels[param] || param}`"
            />
          </el-form-item>

          <el-form-item v-if="form.name === 'GET请求'" label="输入值">
            <el-input v-model="form.params.value" placeholder="请GET请求" />
          </el-form-item>

          <el-form-item v-if="form.name === 'GET请求'" label="等待时间(毫秒)">
            <el-input-number
              v-model="form.params.duration"
              :min="100"
              :step="100"
              style="width: 100%"
            />
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveStep">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang='ts' setup name='filename'>
import { ref, reactive, onMounted, watch, nextTick, markRaw } from 'vue'
//引入用户相关的小仓库
import useUserStore from '@/store/modules/user'
import useSocketClient from '@/store/socket/socket_client'
import emmit from '@/utils/emitter'
import { useRoute, useRouter } from 'vue-router'
import { ElNotification, ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import { VueDraggable } from 'vue-draggable-plus'
// 挂载完毕
//onMounted(()=>{})
//监控数据
//watch(select, (newVal, oldVal) => {})
// 顶部导航栏状态
const activeTab = ref('edit')

// 测试用例名称
const testCaseName = ref('登录成功，下次自动登录')

// 元素操作列表
const elementOperations = markRaw([
  {
    name: 'GET请求',
    label: 'GET请求',
    icon: 'Edit',
    params: { selector: '', value: '' },
  },
  {
    name: 'POST请求',
    label: 'POST请求',
    icon: 'Edit',
    params: { selector: '' },
  },
  {
    name: 'DELETE请求',
    label: 'DELETE请求',
    icon: 'Edit',
    params: { selector: '' },
  },
  {
    name: 'PUT请求',
    label: 'PUT请求',
    icon: 'Edit',
    params: { selector: '', checked: true },
  },
  {
    name: '自定义请求',
    label: '自定义请求',
    icon: 'Edit',
    params: { selector: '', value: '' },
  },
])

// 参数标签映射
const paramLabels: any = {
  selector: '元素定位表达式',
  value: '值',
  duration: '等待时间',
  keys: '按键',
  x: 'X轴偏移',
  y: 'Y轴偏移',
  checked: '是否选中',
}

// 操作图标映射
const operationIcons: any = {
  GET请求: 'edit',
  POST请求: 'mouse',
  DELETE请求: 'delete',
  PUT请求: 'check',
  自定义请求: 'caret-bottom',
}

// 测试步骤数据
const testSteps = ref([
  {
    id: 1,
    name: 'GET请求',
    params: { selector: '#username', value: 'testuser' },
  },
  {
    id: 2,
    name: 'GET请求',
    params: { selector: '#password', value: 'password123' },
  },
  {
    id: 3,
    name: 'POST请求',
    params: { selector: '#login-button' },
  },
])

// 表单配置
const form = reactive({
  id: 0,
  name: '',
  params: {} as any,
})

// 当前编辑的信息
const dialogVisible = ref(false)
const editingStep = ref(null)
const editingStepType = ref('')
const requiredParams = ref<string[]>([])
const optionalParams = ref<string[]>([])
const drag = ref(false)

// 处理拖拽开始
const onDragStart = (e: any, item: any) => {
  e.dataTransfer.setData('operation', JSON.stringify(item))
  e.target.classList.add('dragging')
}

// 处理拖拽结束
const onDragEnd = (e: any) => {
  e.target.classList.remove('dragging')
}

// 处理拖放步骤
const handleStepDrop = (e: any) => {
  e.preventDefault()
  const operationData = JSON.parse(e.dataTransfer.getData('operation'))
  if (operationData) {
    form.name = operationData.name
    // 添加默认描述（如图片中的"输入账号"）
    form.params = {
      ...operationData.params,
      description: operationData.name === 'GET请求' ? '输入账号' : '', // 默认描述
    }
    editingStep.value = null
    editingStepType.value = operationData.name

    // 根据操作类型设置必填参数
    if (operationData.name === 'GET请求') {
      requiredParams.value = ['selector']
      optionalParams.value = ['value']
    } else if (operationData.name === 'POST请求') {
      requiredParams.value = ['selector']
      optionalParams.value = []
    } else if (operationData.name === 'GET请求') {
      requiredParams.value = ['duration']
      optionalParams.value = []
    } else {
      requiredParams.value = []
      optionalParams.value = []
    }

    dialogVisible.value = true
  }
}

// 添加或编辑步骤
const saveStep = () => {
  if (!form.name.trim()) {
    ElMessage.warning('请输入操作名称')
    return
  }

  // 检查必填参数
  for (const param of requiredParams.value) {
    if (!form.params[param]) {
      ElMessage.warning(`请填写${paramLabels[param] || param}`)
      return
    }
  }

  const step = {
    id: form.id || Date.now(),
    name: form.name,
    params: { ...form.params },
  }

  if (editingStep.value !== null) {
    // 更新现有步骤
    testSteps.value[editingStep.value] = step
    ElMessage.success('步骤更新成功')
  } else {
    // 添加新步骤
    testSteps.value.push(step)
    ElMessage.success('步骤添加成功')
  }

  dialogVisible.value = false
}

// 编辑步骤
const editStep = (data: any) => {
  editingStep.value = data.id
  const step = data

  form.id = step.id
  form.name = step.name
  editingStepType.value = step.name
  form.params = { ...step.params }

  // 根据操作类型设置参数
  if (form.name === 'GET请求') {
    requiredParams.value = ['selector']
    optionalParams.value = ['value']
  } else if (form.name === 'POST请求') {
    requiredParams.value = ['selector']
    optionalParams.value = []
  } else if (form.name === 'GET请求') {
    requiredParams.value = ['duration']
    optionalParams.value = []
  } else {
    requiredParams.value = []
    optionalParams.value = []
  }

  dialogVisible.value = true
}

// 删除步骤
const removeStep = (index: any) => {
  testSteps.value.splice(index, 1)
  ElMessage.success('步骤已删除')
}

// 保存测试用例
const saveTestCase = () => {
  if (!testCaseName.value.trim()) {
    ElMessage.warning('请输入用例名称')
    return
  }

  const testCase = {
    name: testCaseName.value,
    steps: testSteps.value,
  }

  console.log('保存用例:', JSON.stringify(testCase, null, 2))

  ElMessage.success('测试用例已保存')
}

// 取消编辑
const cancelEdit = () => {
  // 在实际应用中，这里会导航回用例列表
  ElMessage.info('编辑已取消')
}

// 显示项目列表
const showProjectList = () => {
  ElMessage.info('切换到项目列表')
}
</script>
<style scope lang='scss'>
.test-case-editor {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f7fa;
}

.header {
  background-color: white;
  padding: 0 20px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  z-index: 10;
}

.project-info {
  padding: 12px 0;
  border-bottom: 1px solid #ebeef5;
}

.project-name {
  font-weight: bold;
  margin-right: 15px;
}

.main-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.operation-panel {
  width: 240px;
  background: white;
  border-right: 1px solid #ebeef5;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 16px;
  overflow-y: auto;
}

.panel-title {
  font-size: 16px;
  font-weight: bold;
  padding: 8px 0;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #ebeef5;
}

.panel-title .el-icon {
  margin-right: 8px;
}

.category-container {
  margin-bottom: 20px;
}

.category-title {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
}

.category-title .el-icon {
  margin-right: 8px;
}

.operation-items {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.operation-item {
  position: relative;
  padding: 10px 12px;
  background: white;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  cursor: grab;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  font-size: 13px;
  height: 60px;
}

.operation-item:hover {
  border-color: #409eff;
  background-color: #ecf5ff;
}

.operation-item.dragging {
  opacity: 0.5;
  background-color: #e6f7ff;
  border: 1px dashed #409eff;
}

.operation-icon {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  border-radius: 4px;
  margin-right: 10px;
}

.editor-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.editor-header {
  padding: 16px 24px;
  background: white;
  border-bottom: 1px solid #ebeef5;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.case-name-input {
  font-weight: bold;
}

.steps-container {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: white;
  position: relative;
}

.step-item {
  position: relative;
  padding: 16px;
  margin-bottom: 16px;
  background: #f8fafc;
  border-left: 4px solid #409eff;
  border-radius: 6px;
  transition: all 0.3s;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.step-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.drag-handle {
  margin-right: 10px;
  cursor: move;
  color: #909399;
}

.step-index {
  width: 24px;
  height: 24px;
  background-color: #409eff;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  font-weight: bold;
  font-size: 12px;
}

.step-title {
  font-weight: 500;
  font-size: 14px;
}

.step-details {
  background: white;
  border-radius: 4px;
  padding: 12px;
  border: 1px solid #ebeef5;
  margin-left: 36px;
}

.step-param {
  display: flex;
  margin-bottom: 8px;
  font-size: 13px;
}

.param-key {
  width: 120px;
  color: #909399;
}

.param-value {
  flex: 1;
}

.step-actions {
  position: absolute;
  top: 16px;
  right: 16px;
  display: flex;
  gap: 8px;
}

.empty-placeholder {
  height: 300px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #909399;
  border: 2px dashed #dcdfe6;
  border-radius: 4px;
}

.empty-placeholder .el-icon {
  margin-bottom: 15px;
}

.editor-footer {
  padding: 16px 24px;
  display: flex;
  justify-content: center;
  gap: 12px;
  background: white;
  border-top: 1px solid #ebeef5;
}

.ghost {
  opacity: 0.5;
  background: #c8ebfb;
}

.operation-title {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.operation-icon-large {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #ecf5ff;
  border-radius: 8px;
  margin-right: 12px;
}
</style>